<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-box">
        <div class="login-header">
          <div class="logo-container">
            <img src="@/assets/images/logo-3.jpg" alt="Logo" class="logo">
          </div>
          <h2>物联网数据平台</h2>
          <p class="subtitle">用户登录</p>
        </div>
        
        <el-form 
          ref="formRef"
          :model="form"
          :rules="rules"
          class="login-form"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="form.username"
              placeholder="请输入用户名"
              prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item class="login-btn">
            <el-button 
              type="primary" 
              :loading="loading" 
              class="login-button"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../store/authStore'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const formRef = ref(null)
const loading = ref(false)

const form = ref({
  username: '',
  password: '',
  remember: false
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    const response = await fetch('https://penglink.pcwxcn.top/api/admin/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        name: form.value.username.trim(),
        password: form.value.password
      })
    })

    if (!response.ok) {
      throw new Error('登录失败，请检查网络连接')
    }

    const result = await response.json()
    // console.log('Login response:', result)

    if (result.code === 200) {
      // 处理记住用户名
      if (form.value.remember) {
        localStorage.setItem('rememberedUsername', form.value.username)
      } else {
        localStorage.removeItem('rememberedUsername')
      }

      // 获取用户信息
      const infoResponse = await fetch('https://penglink.pcwxcn.top/api/admin/info', {
        headers: {
          'Authorization': `Bearer ${result.data.token}`,
          'Accept': 'application/json'
        }
      })

      if (!infoResponse.ok) {
        throw new Error('获取用户信息失败')
      }

      const userInfo = await infoResponse.json()
      // console.log('User info:', userInfo)

      if (userInfo.code === 200) {
        // 处理设备权限数据
        let devicesList = [];
        if (userInfo.data.devices) {
          if (Array.isArray(userInfo.data.devices)) {
            devicesList = userInfo.data.devices;
          } else if (typeof userInfo.data.devices === 'string') {
            // 尝试解析字符串形式的devices
            try {
              devicesList = JSON.parse(userInfo.data.devices);
              if (!Array.isArray(devicesList)) {
                devicesList = [devicesList]; // 如果解析后不是数组，则转为数组
              }
            } catch (e) {
              // 如果解析失败，尝试将其作为单个设备ID处理
              devicesList = [userInfo.data.devices];

            }
          } else {
            // 如果是其他类型，尝试转换为数组
            devicesList = [userInfo.data.devices];
          }
        }
        

        
        // 保存登录状态
        authStore.login({
          token: result.data.token,
          role: userInfo.data.role || 'admin',
          userInfo: {
            username: userInfo.data.name,
            nickname: userInfo.data.nickname,
            name: userInfo.data.name,
            id: userInfo.data.id,
            createTime: userInfo.data.createTime,
            remark: userInfo.data.remark,
            devices: devicesList,
            role: userInfo.data.role || 'admin'
          }
        })
        ElMessage.success('登录成功')
        router.push('/user/dashboard')
      } else {
        throw new Error(userInfo.msg || '获取用户信息失败')
      }
    } else {
      throw new Error(result.msg || '登录失败，请检查用户名和密码')
    }
  } catch (error) {

    ElMessage.error(error.message || '登录失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
}

.login-container {
  width: 400px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  z-index: 1;
}

.login-box {
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-container {
  margin: 0 auto;
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
}

.logo {
  width: 100%;
  height: 100%;
}

.login-header h2 {
  margin: 0;
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 16px;
}

.login-form {
  margin-top: 40px;
}

.login-form :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.8);
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.login-btn {
  margin-bottom: 0;
  margin-top: 30px;
}
</style>